package com.gljx.web.controller;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/")
public class MaintainItemAddController {

	//导入activiti工具
	ActitiviUtil activitiUtil = new ActitiviUtil();
	//自动注入
	@Autowired
	private MaintainItemAddService maintainItemAddService;
	//自动注入
	@Autowired
	private DepartmentService departmentService;
	//自动注入
	@Autowired
	private CustomLogService customLogService;
	//自动注入
	@Autowired
	private CarService carService;
	//自动注入
	@Autowired
	private MaintainItemService maintainItemService;

	@Autowired
	private MessageService messageService;

	/**
	 * 查询添加维修项目
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryMaintainItemAdd/look.action")
    public String queryMaintainItemAdd(HttpServletRequest request, String flag) {
        PageBean<MaintainItemAdd> pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//时间格式化
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//获取当前时间
		String endTime = sdf.format(new Date());
		//获取前三天
		String beginTime = TimeFormat.getThreeDay();
		try {
			//获取分页
			pb = getPageBean(request,user.getFcompanyid(),beginTime,endTime);
			//获取分页数据
			List<MaintainItemAdd>  maintainItemAdds = pb.getBeanList();
			for (MaintainItemAdd maintainItemAdd : maintainItemAdds) {
				//获取子类信息
				List<MaintainItemAddEntry> maintainItemAddEntrys = maintainItemAddService.queryMaintainItemAddEntry(maintainItemAdd.getFid(), "", "");
				//放入集合
				maintainItemAdd.setMaintainItemAddEntrys(maintainItemAddEntrys);
			}
			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("maintainItemAdds", maintainItemAdds);
			request.setAttribute("pb", pb);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
            request.setAttribute("flag", flag);
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/carManagement/maintainItemAdd/maintainItemAddList";
	}
	
	/**
	 * 根据条件查询
	 * @param request
	 * @param name 名称
	 * @param carNumber 车牌号码
	 * @param beginTime 业务开始时间
	 * @param endTime 业务结束时间
	 * @return
	 */
	@RequestMapping("/queryMaintainItemAddByInfo")
    public String queryMaintainItemAddByInfo(HttpServletRequest request, String name, String carNumber, String beginTime, String endTime, String fnumber) {
        PageBean<MaintainItemAdd> pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		try {
			//去除空格
			name = name.trim();
            fnumber = fnumber.trim();
            carNumber = carNumber.trim();
			//获取分页
            pb = getPageBean2(request, user.getFcompanyid(), name, carNumber, beginTime, endTime, fnumber);
            //获取分页数据
			List<MaintainItemAdd> maintainItemAdds = pb.getBeanList();
			for (MaintainItemAdd maintainItemAdd : maintainItemAdds) {
				//获取子类信息
				List<MaintainItemAddEntry> maintainItemAddEntrys = maintainItemAddService.queryMaintainItemAddEntry(maintainItemAdd.getFid(), name, carNumber);
				//放入集合
				maintainItemAdd.setMaintainItemAddEntrys(maintainItemAddEntrys);
			}
			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("maintainItemAdds", maintainItemAdds);
			request.setAttribute("pb", pb);
            request.setAttribute("fnumber", fnumber);
            request.setAttribute("name", name);
			request.setAttribute("carNumber", carNumber);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/carManagement/maintainItemAdd/maintainItemAddList";
	}
	
	/**
	 * 跳转到添加页面
	 * @param request
	 * @param type
	 * @return
	 */
	@RequestMapping("/insertMaintainItemAdd")
	public String insertMaintainItemAdd(HttpServletRequest request,String type){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取部门
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//获取最大编码
        /*String fnumber = customLogService.selectFunmber("ct_ds_maintainitemaddnew",user.getFcompanyid());*/
		//获取下一个编码
        String number = GetFnumber.fnumbers("TJWX");
		//获取车辆
		List<Car> cars = carService.queryCar(user.getFcompanyid());
		//获取当前时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//业务时间
		String time = sdf.format(new Date());
		//把数据传到页面
		//request.setAttribute("maintainItems", maintainItems);
		request.setAttribute("time", time);
		request.setAttribute("cars", cars);
		request.setAttribute("type", type);
		request.setAttribute("name", user.getName());
		request.setAttribute("department", department);
		request.setAttribute("fnumber", number);
		return "/backHome/carManagement/maintainItemAdd/editMaintainItemAdd";
	}
	
	/**
	 * 查询维修项目
	 * @return
	 */
	@RequestMapping("/selMaintainItems")
	@ResponseBody
	public List<MaintainItem> selMaintainItems(String name, HttpServletRequest request) {
		List<MaintainItem> maintainItems = new ArrayList<>();
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		if(name == null || "".equals(name)){
			maintainItems = maintainItemService.queryMaintainItem(user.getFcompanyid());
		}else{
			maintainItems = maintainItemService.queryMaintainItemByName(name, user.getFcompanyid());
		}
		return maintainItems;
	}
	
	/**
	 * 添加或修改
	 * @param request
	 * @param fid
	 * @param maintainItemAdd
	 * @return
	 */
	@RequestMapping("/editMaintainItemAdd")
	public String editMaintainItemAdd(HttpServletRequest request,String fid,MaintainItemAdd maintainItemAdd){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//控制单元id
		maintainItemAdd.setFcontrolunitid(user.getFcompanyid());
		//公司id
		maintainItemAdd.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String time = TimeFormat.timeFormat(new Date());
		//操作人id
		maintainItemAdd.setFhandlerid(user.getFid());
		/**获取子类信息集合**/
		//序列
		String[] fseq = request.getParameterValues("fseq");
		//名称
		String[] cfminame = request.getParameterValues("cfminame");
		//车牌号码
		String[] carfnumber = request.getParameterValues("carfnumber");
		//车辆id
		String[] carid = request.getParameterValues("carid");
		//保修期
		String[] cfmibxq = request.getParameterValues("cfmibxq");
		//工时
		String[] cfmigs = request.getParameterValues("cfmigs");
		//单价
		String[] cfmidj = request.getParameterValues("cfmidj");
		//描述
		String[] cfmims = request.getParameterValues("cfmims");
		//添加或修改
		maintainItemAddService.editMaintainItemAdd(maintainItemAdd,fseq,cfminame,carfnumber,carid,cfmibxq,cfmigs,cfmidj,cfmims,user,time);
		if("".equals(fid) || fid == null){
			//添加日志
			customLogService.addLog("车辆管理", time+"对添加维修项目进行添加操作", null, user.getFid());
			//重定向到添加页面
			return "redirect:/DrivingSys/insertMaintainItemAdd?type=3";
		}else{
			//添加日志
			customLogService.addLog("车辆管理", time+"对添加维修项目进行进行修改操作", null, user.getFid());
			//重定向到查询页面
            return "redirect:/DrivingSys/queryMaintainItemAdd/look.action?flag=1";
        }
	}
	
	/**
	 * 根据fid查询
	 * @param request
	 * @param fid
	 * @return
	 */
	@RequestMapping("/queryMaintainItemAddByFid")
	public String queryMaintainItemAddByFid(HttpServletRequest request,String fid){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//查询父类信息
		MaintainItemAdd maintainItemAdd = maintainItemAddService.queryMaintainItemAddByFid(fid);
        if (maintainItemAdd == null) {
            return "/error/not_data";
        } else {
            //查询子类信息
            List<MaintainItemAddEntry> maintainItemAddEntrys = maintainItemAddService.queryMaintainItemAddEntry(fid, "", "");
            //获取车辆
			List<Car> cars = carService.queryCar(maintainItemAdd.getCfficompanyid());
			//把数据传到页面
            //查询是否是经办人
            Axamine axamine = new Axamine();
            String state = axamine.selectAuditPersonByAdd(maintainItemAdd.getFnumber().toString(), ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.MAINTAININTEM_KEY_GL : ActivitiKey.MAINTAININTEM_KEY_NC);
            request.setAttribute("AuditState", state);
			request.setAttribute("activitiBPMN_KEY",ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.MAINTAININTEM_KEY_GL : ActivitiKey.MAINTAININTEM_KEY_NC);
            request.setAttribute("cars", cars);
            request.setAttribute("maintainItemAdd", maintainItemAdd);
            request.setAttribute("maintainItemAddEntrys", maintainItemAddEntrys);
            return "/backHome/carManagement/maintainItemAdd/editMaintainItemAdd";
        }
    }
	
	/**
	 * 根据fid删除
	 * @param request
	 * @param fid
	 * @param deleteId
	 * @return
	 */
	@RequestMapping("/deleteMaintainItemAddByFid")
    public String deleteMaintainItemAddByFid(HttpServletRequest request, String fid, String[] deleteId, String[] fnumber, String fnumber2) {
        //获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//删除
        maintainItemAddService.deleteMaintainItemAddByFid(user,fid, deleteId, fnumber, fnumber2);
        //添加日志
		customLogService.addLog("车辆管理", TimeFormat.timeFormat(new Date())+"对添加维修项目进行进行删除操作", null, user.getFid());
		//重定向到查询页面
		return "redirect:/DrivingSys/queryMaintainItemAdd/look.action";
	}
	
	/**
	 * 审核，反审核
	 * @param request
	 * @param type 1：审核，2：反审核
	 * @param fid
	 * @return
	 */
	@RequestMapping("/auditMaintainItemAdd")
	@ResponseBody
    public int auditMaintainItemAdd(HttpServletRequest request, String type, String fid, String fnumber, String message, String state, String auditState) {
        //获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//审核，反审核
        int i = maintainItemAddService.auditMaintainItemAdd(user,fid, type, user.getFid(), fnumber, message, state, auditState);
        //添加日志
        customLogService.addLog("车辆管理", "对添加维修项目进行进行审核操作单据编号 " + fnumber, null, user.getFid());
        return i;
	}

    /**
     * 提交
	 * 推进流程
	 * @param fid
     * @return
     */
    @RequestMapping("/submitMaintainItemAdd")
    @ResponseBody
	public int submitMaintainItemAdd(String fid, HttpServletRequest request, String fnumber, String auditState) {
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
    	MaintainItemAdd maintainItemAdd = new MaintainItemAdd();
		//推送消息给下一步经办人
		if (!Boolean.valueOf(auditState)) {
			//2.将这个单据编号和你需要保存的流程变量存入map集合中
			Map<String, Object> map = new HashMap<String, Object>();
			map.put(ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.MAINTAININTEM_KEY_GL : ActivitiKey.MAINTAININTEM_KEY_NC, fnumber);//使用你自己单据的key，或者用默认的
			//3.调用方法 flowKey:指定要启动的流程定义 map流程变量
			String piID = activitiUtil.creatFlow(ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.MAINTAININTEM_KEY_GL : ActivitiKey.MAINTAININTEM_KEY_NC, map);
			//4.如果你有“提交”这个流程，那么你还要补上一步，将流程推进到提交的下一步
			Message message = activitiUtil.completeFlowByPiID(piID);
			if (message != null) {
                message.setMessage("添加维修项目-审核 #" + fnumber + " #");//消息内容
                message.setUrl("/queryMaintainItemAddByFid?fid=" + fid + "");//详细路径
				messageService.insert(message);
			}
		} else {
			Message message2 = activitiUtil.complteFlowByVariable(
					ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid()) ? ActivitiKey.MAINTAININTEM_KEY_GL : ActivitiKey.MAINTAININTEM_KEY_NC,  //指定要启动的流程定义
					fnumber                    //流程变量
			);
			if (message2 != null) {
                message2.setMessage("添加维修项目-审核 #" + fnumber + " #");//消息内容
                message2.setUrl("/queryMaintainItemAddByFid?fid=" + fid + "");//详细路径
				messageService.insert(message2);
			}
		}
		/*//获取操作人信息
        User user = (User) request.getSession().getAttribute("user");*/
        maintainItemAdd.setFid(fid);
        maintainItemAdd.setFlastupdateuserid(user.getFid());
        maintainItemAdd.setCfbillstate(4L);
        int i = maintainItemAddService.modifyMaintainItemAdd(maintainItemAdd);
        //添加日志
        customLogService.addLog("车辆管理", "对添加维修项目进行进行提交操作单据编号 " + fnumber, null, user.getFid());
        return i;
    }

    @SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
    public PageBean<MaintainItemAdd> getPageBean2(HttpServletRequest request, String companyId, String name, String carNumber, String beginTime, String endTime, String fnumber) throws Exception {

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select distinct t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name createName,us.name auditName,t.cfbillstate from ");
		psql.append("ct_ds_maintainitemaddnew t left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fauditorid = us.fid ");
		psql.append("left join ct_ds_maintainitemaddnewentry m on m.fparentid = t.fid where t.fcontrolunitid = '"+companyId+"'");
		if("".equals(name)){
			
		}else{
			psql.append(" and m.cfminame like '%"+name+"%'");
		}
		if("".equals(carNumber)){
			
		}else{
			psql.append(" and m.carfnumber like '%"+carNumber+"%'");
		}
        if (fnumber == null || "".equals(fnumber)) {

        } else {
            psql.append(" and t.fnumber like '%" + fnumber + "%'");
        }
        if("".equals(beginTime) || "".equals(endTime)){

		}else{
			psql.append("  and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD')");
		}
        psql.append(" order by to_char(t.fbizdate,'yyyy-MM-dd') desc");
        int psize = 50; //每页显示数
        int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= maintainItemAddService.selectPage(pindex, psql.toString(), psize);
		PageBean<MaintainItemAdd> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<MaintainItemAdd>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}
	
	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
	public PageBean<MaintainItemAdd> getPageBean(HttpServletRequest request,String companyId,String beginTime,String endTime) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name createName,us.name auditName,t.cfbillstate from ");
		psql.append(" ct_ds_maintainitemaddnew t left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fauditorid = us.fid where t.fcontrolunitid = '"+companyId+"'");
		psql.append(" and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD')");
        psql.append(" order by to_char(t.fbizdate,'yyyy-MM-dd') desc");
        int psize = 150; //每页显示数
        int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= maintainItemAddService.selectPage(pindex, psql.toString(), psize);
		PageBean<MaintainItemAdd> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<MaintainItemAdd>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}

	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception
	{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=maintainItemAddService.selectPageCount(psql);
		return paramMap;		
	}

    /**
     * 导出Excel
     *
     * @param request
     * @param response
     * @param name
     * @param carNumber
     * @param beginTime
     * @param endTime
     * @param fnumber
     */
    @RequestMapping("/importMaintainItemAdd")
    public void importMaintainItemAdd(HttpServletRequest request, HttpServletResponse response, String name,
                                      String carNumber, String beginTime, String endTime, String fnumber) {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //定义接收类型
        List<Object> data = new ArrayList<>();
        //查询数据
        List<MaintainItemAddEntry> maintainItemAddEntrys = maintainItemAddService.selectMaintainItemAddByInfo(user.getFcompanyid(), name.trim(), carNumber.trim(), beginTime, endTime, fnumber.trim());
        for (MaintainItemAddEntry maintainItemAddEntry : maintainItemAddEntrys) {
            data.add(maintainItemAddEntry.getFnumber());
            data.add(maintainItemAddEntry.getFbizdate());
            data.add(maintainItemAddEntry.getFdescription());
            data.add(maintainItemAddEntry.getShName());
            data.add(maintainItemAddEntry.getZdrName());
            data.add(stateToString.billsState(maintainItemAddEntry.getCfbillstate()));
            data.add(maintainItemAddEntry.getCfminame());
            data.add(maintainItemAddEntry.getCfmibxq());
            data.add(maintainItemAddEntry.getCfmigs());
            data.add(maintainItemAddEntry.getCfmidj());
            data.add(maintainItemAddEntry.getCarfnumber());
            data.add(maintainItemAddEntry.getCfmims());
        }
        //头部数据
        String head[] = {"单据编号", "业务日期", "参考信息", "审核人名称", "制单人名称", "单据状态", "名称", "保修期", "工时", "单价", "车牌号码", "描述"};
        //长度
        Integer length[] = {8000, 3500, 5000, 3000, 3000, 2800, 8000, 3000, 3000, 3000, 3500, 6000};
        try {
            //导出Excel
            CommonExport.importExcel(response, "添加维修项目" + TimeFormat.getNowTime2() + ".xls", "添加维修项目", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
